package com.briup.cms.config;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.briup.cms.bean.User;
import com.briup.cms.dao.UserDao;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

//Vip定时器类
@Slf4j
@Component
public class VipTimerTask {
    @Autowired
    private UserDao userDao;

    // 每20分钟运行1次
    @Scheduled(cron = "0 0/20 * * * ?")
    public void vipExpirationCheck() {
        //log.info("in VipTimerTask ... " + LocalDateTime.now());
        // 1.获取所有的vip用户
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getIsVip, 1);
        List<User> list = userDao.selectList(wrapper);
        for (User user : list) {
            // 2.判断vip是否过期
            int n = LocalDateTime.now().compareTo(user.getExpiresTime());
            if (n >= 0) {
                // 3.修改过期用户的isVip值
                User u = new User();
                u.setId(user.getId());
                u.setIsVip(0);
                userDao.updateById(u);
            }
        }
    }
}
